from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel
from typing import List, Optional
import uuid
from datetime import datetime

router = APIRouter()

class ShowItem(BaseModel):
    id: str
    name: str
    date: str
    time: str
    venue: str
    address: str
    poster: str
    minPrice: int
    maxPrice: int
    status: str
    priceRange: str

class SessionItem(BaseModel):
    id: str
    date: str
    time: str
    description: str

class RushRequest(BaseModel):
    showId: str
    sessionId: str
    priceRange: str
    ticketCount: int
    rushTime: Optional[datetime] = None
    autoSubmit: bool = True

# 模拟数据
mock_shows = [
    {
        "id": "show001",
        "name": "周杰伦2024巡回演唱会",
        "date": "2024-12-15",
        "time": "19:30",
        "venue": "北京工人体育场",
        "address": "北京市朝阳区工人体育场北路",
        "poster": "https://via.placeholder.com/300x400/4A90E2/FFFFFF?text=周杰伦演唱会",
        "minPrice": 380,
        "maxPrice": 1880,
        "status": "售票中",
        "priceRange": "380-1880"
    },
    {
        "id": "show002",
        "name": "林俊杰圣所2.0演唱会",
        "date": "2024-12-20",
        "time": "19:30",
        "venue": "上海梅赛德斯奔驰文化中心",
        "address": "上海市浦东新区世博大道1200号",
        "poster": "https://via.placeholder.com/300x400/E74C3C/FFFFFF?text=林俊杰演唱会",
        "minPrice": 480,
        "maxPrice": 1680,
        "status": "即将开售",
        "priceRange": "480-1680"
    },
    {
        "id": "show003",
        "name": "五月天2024演唱会",
        "date": "2024-12-25",
        "time": "19:00",
        "venue": "广州天河体育中心",
        "address": "广州市天河区天河路299号",
        "poster": "https://via.placeholder.com/300x400/2ECC71/FFFFFF?text=五月天演唱会",
        "minPrice": 280,
        "maxPrice": 1580,
        "status": "预售中",
        "priceRange": "280-1580"
    }
]

mock_sessions = {
    "show001": [
        {"id": "session001", "date": "2024-12-15", "time": "19:30", "description": "第一场"},
        {"id": "session002", "date": "2024-12-16", "time": "19:30", "description": "第二场"},
        {"id": "session003", "date": "2024-12-17", "time": "19:30", "description": "第三场"}
    ],
    "show002": [
        {"id": "session004", "date": "2024-12-20", "time": "19:30", "description": "上海站"},
        {"id": "session005", "date": "2024-12-21", "time": "19:30", "description": "上海站加场"}
    ],
    "show003": [
        {"id": "session006", "date": "2024-12-25", "time": "19:00", "description": "广州站"}
    ]
}

@router.get("/search")
async def search_shows(
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    city: Optional[str] = Query(None, description="城市"),
    category: Optional[str] = Query(None, description="分类")
):
    """搜索演出"""
    results = mock_shows
    
    if keyword:
        results = [show for show in results if keyword.lower() in show["name"].lower()]
    
    if city:
        results = [show for show in results if city in show["venue"]]
    
    return {"shows": results}

@router.get("/show/{show_id}")
async def get_show_detail(show_id: str):
    """获取演出详情"""
    show = next((s for s in mock_shows if s["id"] == show_id), None)
    if not show:
        raise HTTPException(status_code=404, detail="演出不存在")
    return show

@router.get("/sessions/{show_id}")
async def get_sessions(show_id: str):
    """获取演出场次"""
    sessions = mock_sessions.get(show_id, [])
    return sessions

@router.post("/rush")
async def start_rush(request: RushRequest):
    """开始抢票"""
    # 模拟抢票过程
    import random
    import time
    
    # 模拟网络延迟
    time.sleep(random.uniform(1, 3))
    
    # 模拟成功率
    success = random.random() > 0.3
    
    if success:
        order_id = f"ORDER{uuid.uuid4().hex[:8].upper()}"
        return {
            "success": True,
            "orderId": order_id,
            "message": "抢票成功",
            "timestamp": datetime.now()
        }
    else:
        return {
            "success": False,
            "message": "库存不足或网络超时",
            "timestamp": datetime.now()
        }

@router.get("/price/{show_id}/{session_id}")
async def get_price_ranges(show_id: str, session_id: str):
    """获取价位信息"""
    # 模拟价位数据
    prices = [
        {"id": "price001", "range": "280元", "count": 0},
        {"id": "price002", "range": "380元", "count": 5},
        {"id": "price003", "range": "580元", "count": 12},
        {"id": "price004", "range": "780元", "count": 8},
        {"id": "price005", "range": "980元", "count": 15},
        {"id": "price006", "range": "1280元", "count": 3}
    ]
    return {"prices": prices}